package com.example.hxds.odr.service.impl;

import cn.hutool.core.map.MapUtil;
import com.codingapi.txlcn.tc.annotation.LcnTransaction;
import com.example.hxds.common.exception.HxdsException;
import com.example.hxds.odr.db.dao.OrderBillDao;
import com.example.hxds.odr.db.dao.OrderDao;
import com.example.hxds.odr.db.pojo.OrderBillEntity;
import com.example.hxds.odr.db.pojo.OrderEntity;
import com.example.hxds.odr.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: OrderServiceImpl
 * @Description: 司机订单实现类
 * @Author: 丛雨
 * @Date: 2024/1/20 15:07
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Resource
    private OrderDao orderDao;

    @Resource
    private OrderBillDao orderBillDao;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 创建新订单
     *
     * @param orderEntity     订单实体类
     * @param orderBillEntity 订单账单实体类
     * @return 创建订单的结果
     */
    @Override
    @Transactional
    @LcnTransaction
    public String insertOrder(OrderEntity orderEntity, OrderBillEntity orderBillEntity) {
        int rows = orderDao.insert(orderEntity);
        if (rows == 1) {
            String orderId = orderDao.searchOrderIdByUUID(orderEntity.getUuid());
            orderBillEntity.setOrderId(Long.parseLong(orderId));
            rows = orderBillDao.insert(orderBillEntity);
            if (rows == 1) {
                // 向redis缓存订单Id,配合Redis事务用于司机抢单
                redisTemplate.opsForValue().set("order#" + orderId, "none");
                redisTemplate.expire("order#" + orderId, 15, TimeUnit.MINUTES);
                return orderId;
            } else {
                throw new HxdsException("创建新订单账单失败");
            }
        } else {
            throw new HxdsException("创建新订单失败");
        }
    }

    /**
     * 查询司机当日订单数据
     *
     * @param driverId 司机Id
     * @return 查询结果
     */
    @Override
    public HashMap searchDriverTodayBusinessDateData(long driverId) {
        HashMap result = orderDao.searchDriverTodayBusinessDateData(driverId);

        // 当返回的值为null,JSON传输时会忽略null值,我们需要手动将其设定为String字符串s
        String duration = MapUtil.getStr(result, "duration");
        if (duration == null) {
            duration = "0";
        }
        result.replace("duration", duration);

        String income = MapUtil.getStr(result, "income");
        if (income == null) {
            income = "0.00";
        }
        result.replace("income", income);

        return result;
    }
}
